#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <fstream>
#include <unordered_map>
#include <signal.h>
#include <cstdio>

static void Usage(std::string proc)
{
    std::cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}

OnlineUser onlineuser;

void routeMessage(int sockfd, std::string clientip, uint16_t clientport, std::string message)
{
    if (message == "online") onlineuser.addUser(clientip, clientport);
    if (message == "offonline") onlineuser.delUser(clientip, clientport);

    if (onlineuser.isOnline(clientip, clientport))
    {   //将消息转发给所有在线的用户
        onlineuser.broadcastMessage(sockfd, clientip, clientport, message);
    }
    else
    {
        //若不在线，则单独给不在线的用户发一条消息
        struct sockaddr_in server_send;

        server_send.sin_family = AF_INET;
        server_send.sin_port = htons(clientport);
        server_send.sin_addr.s_addr = inet_addr(clientip.c_str());

        std::string respond = "你还没有上线, 请输入 online 上线";
        sendto(sockfd, respond.c_str(), respond.size(), 0, (struct sockaddr*)&server_send, sizeof(server_send));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]); // 字符型转换为uint16_t

    std::unique_ptr<Server> usvr(new Server(routeMessage, port));

    usvr->initServer();
    usvr->start();

    return 0;
}